package com.houfukude.Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;

import Utils.V;
import android.util.Log;

public class FTP_Client {
	private String DEBUG_TAG = "Ftp_Client";
	private FTPClient ftpClient;
	private FTPFile[] list_with_dir;
	private ArrayList<FTPFile> files = new ArrayList<FTPFile>();
	private String path = V.DIR + "/";
	private String host = "192.168.43.1";
	private int port = 2221;
	private String usr = "anonymous";
	private String pwd = null;

	public void setHost(String host) {
		this.host = host;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public void setUsr(String usr) {
		this.usr = usr;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	/**
	 * 
	 * 初始化ftpclient链接 <br>
	 * ！！ 耗时操作 需要在线程中执行！！
	 * 
	 * @param pathname
	 */
	public synchronized void Initalize(String pathname) {
		try {
			synchronized (this) {
				ftpClient = new FTPClient();
				ftpClient.connect(host, port);
				boolean result = ftpClient.login(usr, pwd);
				if (false != result) {
					ftpClient.setControlEncoding("UTF-8");
					FTPClientConfig config = new FTPClientConfig(ftpClient
							.getSystemName().split(" ")[0]);
					config.setServerLanguageCode("zh");
					ftpClient.configure(config);
					ftpClient.enterLocalPassiveMode();
					ftpClient
							.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);

					if (pathname != null) {
						ftpClient.changeWorkingDirectory(pathname);
					}

					list_with_dir = ftpClient.listFiles();
					files.removeAll(files);
					for (int i = 0; i < list_with_dir.length; i++) {
						if (list_with_dir[i].getType() == 0) {
							Log.i(DEBUG_TAG,
									"File :" + list_with_dir[i].getName()
											+ " size :"
											+ list_with_dir[i].getSize());
							files.add(list_with_dir[i]);
						}
					}
				}
			}
		} catch (IOException e) {
		}
	}

	public ArrayList<FTPFile> getFiles() {
		return files;
	}

	public void setPath(String path) {
		this.path = path;
	}

	/**
	 * 获取文件到指定path<br>
	 * 先FTP_Client.Instance() ！！ 耗时操作 需要在线程中执行！！
	 * 
	 * @param index
	 * @return
	 */
	public synchronized Boolean get(int index) {
		try {
			synchronized (this) {
				String src = path + files.get(index).getName();
				Log.i(DEBUG_TAG, "GET :" + src);
				File file = new File(src);
				FileOutputStream fos = new FileOutputStream(file);
				return ftpClient.retrieveFile(files.get(index).getName(), fos);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
		}
		return false;
	}

}
